/**
 * Description
 *
 * Creation Date 27/10/2017
 * @author Candy
 */

'use strict'
import Basecomponent from '../../prototype/baseComponent'
import OrderModel from '../../models/v1/order'
import formidable from 'formidable'
import dtime from 'time-formater'

class Order extends Basecomponent {
    constructor() {
        super()
        this.addOrder = this.addOrder.bind(this)
    }
    async addOrder(req, res, next) {
        const qid = req.query.user_id
        const sid = req.session.user_id
        const user_id = qid || sid;
        const form = new formidable.IncomingForm()
        form.parse(req, async(err, fields, files) => {
            const {total, cart, address} = fields
            try {
                const id = await this.getId('order_id')
                const order_id = 'CN' + Date.now()
                const order_time = dtime().format('YYYY-MM-DD HH:mm')
                const ispayment = false
                const remark = 'remark'
                const orderInfo = {
                    id,
                    user_id,
                    order_id,
                    total,
                    order_time,
                    remark,
                    ispayment,
                    cart,
                    address
                }
                await OrderModel.create(orderInfo)
                res.send({
                    id,
                    status: 1,
                    message: 'Order is successful'
                })
            } catch (err) {
                res.send({
                    status: 0,
                    type: 'ERROR_ORDER',
                    message: 'Order is fail'
                })
            }
        })
    }
    async getOrderById(req, res, next) {
        const qid = req.query.user_id
        const sid = req.session.user_id
        const user_id = qid || sid;
        const order_id = req.query.order_id
        try {
            const orderInfo = await OrderModel.findOne({id: order_id, user_id}, '-_id')
            res.send(orderInfo)
        } catch (err) {
            res.send({
                status: 0,
                type: 'ERROR_GET_ORDER',
                message: 'Get order fail'
            })
        }
    }
    async getOrdersList(req, res, next) {
        const qid = req.query.user_id
        const sid = req.session.user_id
        const user_id = qid || sid;
        const {limit = 10, offset =0} = req.query
        try {
            const orderInfo = await OrderModel.find({user_id}, '-_id').sort({id:-1}).limit(10).skip(offset)
            res.send(orderInfo)
        } catch (err) {
            res.send({
                status: 0,
                type: 'ERROR_GET_ORDER',
                message: 'Get order fail'
            })
        }
    }
}

export default new Order()
